import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login.vue'
import register from '../views/register.vue'
import detail from '../views/detail.vue'
import layout from '../views/layout.vue'
import article from '../views/article.vue'
import like from '../views/like.vue'
import collect from '../views/collect.vue'
import user from '../views/user.vue'
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: login
  },
  {
    path: '/register',
    component: register
  },
  {
    path: '/detail/:id',
    component: detail
  },
  {
    path: '/',
    component: layout,
    redirect: '/article',
    children: [
      {
        path: '/article',
        component: article
      },
      {
        path: '/like',
        component: like
      },
      {
        path: '/collect',
        component: collect
      },
      {
        path: '/user',
        component: user
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register']
// 全局前置守卫
router.beforeEach((to, from, next) => {
  const token = getToken()
  // 判断有没有 token 有直接放行,没有 token 判断访问的页面在不在白名单 在白名单也直接放行 否则直接跳转到首页
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Toast.fail('登陆过期,请重新登录')
      next('/login')
    }
  }
})

export default router
